﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;
using ComponentFactory.Krypton.Toolkit;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;

    public partial class RepositoryForm : Form
    {
        private class ColumnIndex
        {
            public const int Id = 0;
            public const int Name = 1;
            public const int Email = 2;
            public const int Owner = 3;
            public const int IsActive = 4;
        }

        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("RepositoryForm");
        private IRepository<Repository> repositoryRepository = null;
        private IList<Repository> listOfRepositories = null;
        private IList<Repository> listOfRepositoriesToDelete = null;

        #region Constructors

        public RepositoryForm()
        {
            InitializeComponent();

            this.SetUp();
            this.LoadData();
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Setup the data grid
        /// </summary>
        private void SetUp()
        {
            this.repositoryRepository = Program.Container.Resolve<IRepository<Repository>>();

            this.kdgvRepositories.AutoGenerateColumns = false;
            var idColumn = new DataGridViewColumn
            {
                DataPropertyName = Repository.Properties.Id,
                Name = Repository.Properties.Id,
                HeaderText = "Id",
                ValueType = typeof(int),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = false
            };
            this.kdgvRepositories.Columns.Add(idColumn);

            var nameColumn = new DataGridViewColumn
            {
                DataPropertyName = Repository.Properties.Name,
                Name = Repository.Properties.Name,
                HeaderText = "Repository Name",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 150
            };
            this.kdgvRepositories.Columns.Add(nameColumn);

            var emailColumn = new DataGridViewColumn
            {
                DataPropertyName = Repository.Properties.Email,
                Name = Repository.Properties.Email,
                HeaderText = "Email",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 100
            };
            this.kdgvRepositories.Columns.Add(emailColumn);

            var ownerColumn = new DataGridViewColumn
            {
                DataPropertyName = Repository.Properties.Owner,
                Name = Repository.Properties.Owner,
                HeaderText = "Owner",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true
            };
            this.kdgvRepositories.Columns.Add(ownerColumn);

            var isActiveColumn = new DataGridViewColumn
            {
                DataPropertyName = Repository.Properties.IsActive,
                Name = Repository.Properties.IsActive,
                HeaderText = "Is active",
                ValueType = typeof(bool),
                CellTemplate = new DataGridViewCheckBoxCell(false),
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Alignment = DataGridViewContentAlignment.MiddleCenter
                },
                Visible = true
            };
            this.kdgvRepositories.Columns.Add(isActiveColumn);
        }

        /// <summary>
        /// Load all repositories from database
        /// </summary>
        private void LoadData()
        {
            this.listOfRepositories = this.repositoryRepository.FindAll();
            if (this.listOfRepositories == null)
            {
                this.listOfRepositories = new List<Repository>();
            }

            foreach (Repository repositoryItem in this.listOfRepositories)
            {
                this.DisplayRepositoryData(repositoryItem);
            }
        }

        private void AddOrUpdateRepository(Repository repositoryItem)
        {
            if (repositoryItem != null)
            {
                Repository existingRepository = this.listOfRepositories.FirstOrDefault(item => ((item.Id == repositoryItem.Id) || (item.Name == repositoryItem.Name)));
                if (existingRepository == null)
                {
                    this.listOfRepositories.Add(repositoryItem);
                    this.DisplayRepositoryData(repositoryItem);
                }
                else
                {
                    existingRepository = repositoryItem;
                    this.UpdateRepositoryData(repositoryItem);
                }
            }
        }

        private void DisplayRepositoryData(Repository repositoryItem)
        {
            if (repositoryItem != null)
            {
                this.kdgvRepositories.Rows.Add(repositoryItem.Id, repositoryItem.Name, repositoryItem.Email, repositoryItem.Owner.FullName, repositoryItem.IsActive);
            }
        }

        private void UpdateRepositoryData(Repository repositoryItem)
        {
            if (repositoryItem != null)
            {
                foreach (DataGridViewRow rowItem in this.kdgvRepositories.Rows)
                {
                    if (repositoryItem.Id.Equals(rowItem.Cells[ColumnIndex.Id].Value)
                        && repositoryItem.Email.Equals(rowItem.Cells[ColumnIndex.Email].Value))
                    {
                        rowItem.Cells[ColumnIndex.Name].Value = repositoryItem.Name;
                        rowItem.Cells[ColumnIndex.Email].Value = repositoryItem.Email;
                        rowItem.Cells[ColumnIndex.Owner].Value = repositoryItem.Owner.FullName;
                        rowItem.Cells[ColumnIndex.IsActive].Value = repositoryItem.IsActive;

                        break;
                    }
                }
            }
        }

        private void ShowAccountForm(DataGridViewRow rowItem)
        {
            int accountId = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
            string email = Convert.ToString(rowItem.Cells[ColumnIndex.Email].Value);

            Repository accountItem = this.listOfRepositories.FirstOrDefault(item => ((item.Id == accountId) && (item.Email == email)));
            using (RepositoryFormEdit accountForm = new RepositoryFormEdit(accountItem, RepositoryFormEdit.EditModes.OwnerFocus)
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = accountForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.AddOrUpdateRepository(accountForm.SelectedRepository);
                }
            }
        }

        private DialogResult ConfirmRemoveRepositories()
        {
            var result = DialogResult.None;
            if (this.kdgvRepositories.SelectedRows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Are you sure you want to delete these repositories:");
                sb.AppendLine();
                foreach (DataGridViewRow rowItem in this.kdgvRepositories.SelectedRows)
                {
                    sb.AppendFormat("   {0}", rowItem.Cells[ColumnIndex.Name].Value);
                    sb.AppendLine();
                }

                result = KryptonMessageBox.Show(sb.ToString(), "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }

            return result;
        }

        #endregion

        #region Events

        private void btnAddRepository_Click(object sender, EventArgs e)
        {
            using (var repositoryForm = new RepositoryFormEdit()
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = repositoryForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.AddOrUpdateRepository(repositoryForm.SelectedRepository);
                }
            }
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listOfRepositoriesToDelete != null)
                {
                    foreach (Repository repositoryItem in this.listOfRepositoriesToDelete)
                    {
                        repositoryItem.Delete();
                    }
                }

                if (this.listOfRepositories != null)
                {
                    foreach (Repository repositoryItem in this.listOfRepositories)
                    {
                        repositoryItem.Save();
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
                this.Dispose();
                GC.SuppressFinalize(this);
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.No;
                _logger.Error("Error while saving changes", ex);
            }
        }

        private void kdgvRepositories_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                case ColumnIndex.Owner:
                    e.Cancel = true;

                    try
                    {
                        this.ShowAccountForm(this.kdgvRepositories.Rows[e.RowIndex]);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Error while preparing account edit form", ex);
                    }

                    break;
            }
        }

        private void kdgvRepositories_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridViewCell modifiedCell = this.kdgvRepositories.Rows[e.RowIndex].Cells[e.ColumnIndex];

                int repositoryId = Convert.ToInt32(this.kdgvRepositories.Rows[e.RowIndex].Cells[ColumnIndex.Id].Value);
                Repository selectedRepository = this.listOfRepositories.FirstOrDefault(repositoryItem => repositoryItem.Id == repositoryId);

                switch (e.ColumnIndex)
                {
                    case ColumnIndex.Email:
                        selectedRepository.Email = Convert.ToString(modifiedCell.Value);
                        break;
                    case ColumnIndex.Name:
                        selectedRepository.Name = Convert.ToString(modifiedCell.Value);
                        break;
                    case ColumnIndex.IsActive:
                        selectedRepository.IsActive = Convert.ToBoolean(modifiedCell.Value);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat(ex, "Error while editing cell: {0}", e.ColumnIndex);
            }
        }

        private void kdgvRepositories_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (this.ConfirmRemoveRepositories() != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }

        private void kdgvRepositories_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            int id = Convert.ToInt32(e.Row.Cells[ColumnIndex.Id].Value);
            string name = Convert.ToString(e.Row.Cells[ColumnIndex.Name].Value);
            Repository repositoryItem = this.listOfRepositories.FirstOrDefault(item => ((item.Id == id) && (item.Name == name)));

            if (this.listOfRepositoriesToDelete == null)
            {
                this.listOfRepositoriesToDelete = new List<Repository>();
            }
            this.listOfRepositoriesToDelete.Add(repositoryItem);
            this.listOfRepositories.Remove(repositoryItem);
        }

        private void updateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.kdgvRepositories.CurrentRow != null)
                {
                    this.ShowAccountForm(this.kdgvRepositories.CurrentRow);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error while updating account", ex);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ConfirmRemoveRepositories() == DialogResult.Yes)
            {
                foreach (DataGridViewRow rowItem in this.kdgvRepositories.SelectedRows)
                {
                    this.kdgvRepositories.Rows.Remove(rowItem);

                    int id = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                    string name = Convert.ToString(rowItem.Cells[ColumnIndex.Name].Value);
                    Repository repositoryItem = this.listOfRepositories.FirstOrDefault(item => ((item.Id == id) && (item.Name == name)));

                    if (this.listOfRepositoriesToDelete == null)
                    {
                        this.listOfRepositoriesToDelete = new List<Repository>();
                    }
                    this.listOfRepositoriesToDelete.Add(repositoryItem);
                    this.listOfRepositories.Remove(repositoryItem);
                }
            }
        }

        #endregion

    }
}
